package event.key;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class KeyEventFrame extends JFrame {

    JPanel jp;

    int x = 10,y = 10;

    public KeyEventFrame(){
        this.setSize(500, 500);
        this.setDefaultCloseOperation(3);
        this.setLocationRelativeTo(null);
        this.setLayout(null);

        jp = new JPanel();
        jp.setBounds(x,y, 50, 50);
        jp.setBackground(Color.red);

        this.addKeyListener(new KeyListener() {
            // 被按下unicode码的字符（特殊字符被按下不会调用）
            @Override
            public void keyTyped(KeyEvent e) {
//                char code = e.getKeyChar();
//                System.out.println(code);
            }

            // 键盘被按下
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_UP || e.getKeyChar() == 'w'){
                    y -= 5;
                    jp.setBounds(x,y, 50, 50 );
                }else if(e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyChar() == 's'){
                    y += 5;
                    jp.setBounds(x,y, 50, 50 );
                }else if(e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyChar() == 'a'){
                    x -= 5;
                    jp.setBounds(x,y, 50, 50 );
                }else if(e.getKeyCode() == KeyEvent.VK_RIGHT|| e.getKeyChar() == 'd'){
                    x += 5;
                    jp.setBounds(x,y, 50, 50 );
                }
            }

            //键盘被释放
            @Override
            public void keyReleased(KeyEvent e) {

            }
        });

        this.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
               jp.setBounds(e.getX()-20, e.getY()-50, 50, 50);
            }
        });

        this.add(jp);
        this.setVisible(true);
    }

    public static void main(String[] args){
        new KeyEventFrame();
    }
}
